package com.mentalhealthplatform.global.redisGuard;

import lombok.Getter;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @author Pear
 */
@Service
public class CacheService {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private DatabaseService databaseService;

    public <T> T getCacheData(String key, Class<T> type) {
        Object value = redisTemplate.opsForValue().get(key);
        if (value == null) {
            return null;
        }

        // 检查是否为空对象
        if (value instanceof CacheObject) {
            CacheObject cacheObject = (CacheObject) value;
            if (cacheObject.isLogicalExpire()) {
                return null;
            }
            return type.cast(cacheObject.getData());
        } else if (value instanceof Map) {
            // 手动将 LinkedHashMap 转换为 CacheObject
            Map<String, Object> map = (Map<String, Object>) value;
            CacheObject cacheObject = new CacheObject();
            cacheObject.setData(map.get("data"));
            cacheObject.setExpireTime((Long) map.get("expireTime"));
            cacheObject.setLogicalExpire((Boolean) map.get("logicalExpire"));

            if (cacheObject.isLogicalExpire()) {
                return null;
            }
            return type.cast(cacheObject.getData());
        } else {
            // 其他情况直接返回 null 或抛出异常
            return null;
        }
    }

    public <T> void setCacheData(String key, T data, long timeout, TimeUnit timeUnit) {
        CacheObject<T> cacheObject = new CacheObject<>();
        cacheObject.setData(data);
        cacheObject.setExpireTime(System.currentTimeMillis() + timeUnit.toMillis(timeout));
        // 初始化逻辑过期标志为 false
        cacheObject.setLogicalExpire(false);

        // 设置随机增加的过期时间
        Random random = new Random();
        int randomTimeout = (int) (timeout + random.nextInt(1000));

        redisTemplate.opsForValue().set(key, cacheObject, randomTimeout, timeUnit);
    }

    public <T> T getDbData(String key, Class<T> type) {
        return databaseService.getDataFromDatabase(key, type);
    }

    @Getter
    @Setter
    private static class CacheObject<T> {
        private T data;
        private long expireTime;
        private Boolean logicalExpire;

        public boolean isLogicalExpire() {
            return System.currentTimeMillis() > expireTime;
        }
    }
}
